package com.wxlsoft.utils;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipException;

public class FilesUtli {

	/**
	 * 移动文件
	 * @param sources
	 * @param target
	 * @throws IOException
	 */
	public static Path move(Path sources, Path target) throws IOException {
		File t = target.toFile()
				.getParentFile();
		if (!t.exists()) {
			t.mkdirs();
		}
		Path move = Files.move(sources, target, StandardCopyOption.REPLACE_EXISTING);
		return move;
	}

	/**
	 * 移动文件
	 * @param sources
	 * @param target
	 * @throws IOException
	 */
	public static void copy(Path sources, Path target) throws IOException {
		mkParentdirs(target.toFile());
		Files.copy(sources, target, StandardCopyOption.REPLACE_EXISTING);
	}	
	
	/**
	 * 创建父级目录
	 * @param file
	 */
	public static void mkParentdirs(File file) {
		File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
	}
	
	/**
	 * 生成文件
	 * @param path
	 * @throws IOException
	 */
	public static void create(Path path) {
		File file = path.toFile();
		if (file.exists()) {
			file.delete();
		}
		File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		try {
			file.createNewFile();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 删除指定文件或目录
	 * @param files
	 * @throws Throwable
	 */
	public static void removeFiles(List<File> files) {
		for (File f : files) {
			deleteFiles(f);
		}
	}
	
	private static void deleteFiles(File f) {
		if (f.isDirectory()) {
            for(File cf: f.listFiles()){  
            	deleteFiles(cf);  
            }
            f.delete();
		} else {
			f.delete();
		}
	}

	/**
	 * 过滤不需要的文件
	 * @param path
	 * @param readHiddenFiles
	 * @return
	 * @throws ZipException
	 */
	public static List<File> getFilesInDirectoryRec(File path, 
			boolean readHiddenFiles, FilenameFilter filter) {
		
		List<File> result = new LinkedList<>();
		File[] filesAndDirs = Objects.isNull(filter) 
				? path.listFiles() 
				: path.listFiles(filter);
		List<File> filesDirs = Arrays.asList(filesAndDirs);
		
		if (!path.canRead()) {
			return result; 
		}
		
		for(int i = 0; i < filesDirs.size(); i++) {
			File file = (File)filesDirs.get(i);
			if (file.isHidden() && !readHiddenFiles) {
				continue;
			}
			result.add(file);
			if (file.isDirectory()) {
				List<File> deeperList = getFilesInDirectoryRec(file, readHiddenFiles, filter);
				result.addAll(deeperList);
			}
	    }
		return result;
	}
	
}
